<?php


namespace app\admin\logic\zhxy;

use app\common\library\Logger;

class GetAccessToken

{

    private   $path        = '';
    protected $noNeedLogin = [ '*' ];

    /**
     * 获取token
     */
    private function gettoken($is_refresh = false,$type = null)
    {
        //加载初始化配置
        switch ($type) {
            case 'friend':
                $appid       = config('zhxy.friend_appid');
                $appsecret   = config('zhxy.friend_appsecret');
                break;
            case 'outside':
                $appid       = config('zhxy.outside_appid');
                $appsecret   = config('zhxy.outside_appsecret');
                break;
            default:
                $appid       = '';
                $appsecret   = '';
                break;
        }
        $domain      = config('zhxy.school_url');
        $url         = config('zhxy.get_token');
        $m_shool_url = $domain . $url;
        //构建接口URL
        $url = $m_shool_url . "?appid={$appid}&appsecret={$appsecret}";

        //请求接口(推荐使用curl)
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);

        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);
        // Logger::debug("GetAccessToken  " . $data);

        $res = json_decode($data, true);
        if ($res['e'] == 0) {
            $str = $res['d']['access_token'] . "\n" . time();
            // Logger::debug("GetAccessToken  " . $str);
            file_put_contents($this->path, $str);
            return $res['d']['access_token'];
        } else {
            // Logger::error("GetAccessToken error ");
            return false;
        }
    }

    // 获取token
    public function get_token($type = null)
    {
        $path       = APP_PATH . 'token';
        $this->path = $path . DS . 'zhxy_token.txt';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if (!file_exists($this->path)) {
            // 请求接口获取token
            return $this->gettoken(false,$type);
        }
        $token_str = file_get_contents($this->path);
        if (!empty($token_str)) {
            $token_arr = explode("\n", $token_str);
            if (time() - $token_arr[1] > config('zhxy')['expires_in']) {
                // 刷新token
                return $this->gettoken(false,$type);
            }
            if (is_array($token_arr)) {
                if (empty($token_arr[0])) {
                   return $this->gettoken(false,$type);
                }
                return $token_arr[0];
            } else {
                return 'error!';
            }
        }

        return $this->gettoken(false,$type);
    }


}